package com;

/**
 * 给定两个单词 word1 和 word2，计算出将 word1 转换成 word2 所使用的最少操作数 。
 *
 * 你可以对一个单词进行如下三种操作：
 *
 * 插入一个字符
 * 删除一个字符
 * 替换一个字符
 * 示例 1:
 *
 * 输入: word1 = "horse", word2 = "ros"
 * 输出: 3
 * 解释:
 * horse -> rorse (将 'h' 替换为 'r')
 * rorse -> rose (删除 'r')
 * rose -> ros (删除 'e')
 * 示例 2:
 *
 * 输入: word1 = "intention", word2 = "execution"
 * 输出: 5
 * 解释:
 * intention -> inention (删除 't')
 * inention -> enention (将 'i' 替换为 'e')
 * enention -> exention (将 'n' 替换为 'x')
 * exention -> exection (将 'n' 替换为 'c')
 * exection -> execution (插入 'u')
 *
 * @author YL
 **/
public class StrToStrLink {

    public int minDistance(String word1, String word2) {
        int length1 = word1.length();
        int length2 = word2.length();

        int[][] db = new int[length1 + 1][length2 + 1];

        // 初始化零行 零列
        for (int i = 1; i <= length1; i++) {
            db[i][0] = db[i - 1][0] + 1;
        }
        for (int i = 1; i <= length2; i++) {
            db[0][i] = db[0][i - 1] + 1;
        }

        for (int i1 = 1; i1 <= length1; i1++) {
            for (int i2 = 1; i2 <= length2; i2++) {
                if (word1.charAt(i1 - 1) == word2.charAt(i2 - 1)) {
                    db[i1][i2] = db[i1 - 1][i2 - 1];
                } else {
                    db[i1][i2] = Math.min(Math.min(db[i1][i2 -1], db[i1 - 1][i2]), db[i1 - 1][i2 - 1]) + 1;
                }
            }
        }
        return db[length1][length2];
    }

    public static void main(String[] args) {
        System.out.println(new StrToStrLink().minDistance("0000", "1101"));
        System.out.println(new StrToStrLink().minDistance("plasma", "altruism"));
        System.out.println(new StrToStrLink().minDistance("horse", "ros"));
        System.out.println(new StrToStrLink().minDistance("12333", "333"));
        System.out.println(new StrToStrLink().minDistance("12333", "12333"));
    }
}
